﻿using Activity.Data;
using Activity.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web.Configuration;
using static Activity.Helper.CommHelper;

namespace Activity.API
{
    /// <summary>
    /// 新店开业抽奖活动
    /// </summary>
    public class OpenShopLotteryHandler
    {
        /// <summary>
        /// 结束时间
        /// </summary>
        static readonly DateTime endDate = new DateTime(2017, 04, 29, 23, 59, 59);

        /// <summary>
        /// 开始时间
        /// </summary>
        static readonly DateTime beginDate = new DateTime(2017, 04, 28, 0, 0, 0);

        /// <summary>
		/// 使用的Redis数据库索引
		/// </summary>
		public const int RedisDatabaseIndex = 4;

        /// <summary>
        /// 每天递减的奖品比例
        /// </summary>
        static readonly int[] LotteryRate = new int[] { 35, 25, 20, 20 };

        /// <summary>
        /// 测试
        /// </summary>
        static readonly string isDebug = WebConfigurationManager.AppSettings["isDebug"];

        /// <summary>
        /// 兑奖
        /// </summary>
        /// <param name="openID"></param>
        /// <returns></returns>
        public int CashPrize(string openID)
        {
            var dc = new ActivityEntities();
            var qurey = dc.Bas_WxOrders.FirstOrDefault(t => t.openid == openID);
            qurey.Finished = true;
            try
            {
                dc.SaveChanges();
                return 0;
            }catch(Exception ex)
            {
                Log.Error(ex.Message);
                return -1;
            }
        }

        /// <summary>
        /// 获取中奖情况
        /// </summary>
        /// <param name="openID"></param>
        /// <returns></returns>
        public Messages GetLottery(string openID)
        {
            var dc = new ActivityEntities();
            var qurey = dc.Bas_WxOrders.Where(t => t.openid == openID);
            if (!qurey.Any()) return new Messages { IsSuc = false, Code = -1, Message ="您还没有抽奖！"};
            var result = qurey.FirstOrDefault();
            if (result.Finished == false) return new Messages { IsSuc = true, Code = 0, Message = result.pid.ToString() };
            else return new Messages { IsSuc = true, Code = 1, Message = result.pid.ToString() };
        }
        /// <summary>
        /// 抽奖
        /// </summary>
        /// <param name="openID"></param>
        /// <returns></returns>
        public Messages DrawPrize(string openID = "")
        {
            try
            {
                if (string.IsNullOrWhiteSpace(openID)) return new Messages { IsSuc = false, Code = -1, Message = "无效的OPENID" };
                if (DateTime.Now < beginDate && isDebug.ToLower() == "false")
                {
                    return new Messages { IsSuc = false, Code = -1, Message = "亲，活动还没开始呢" };
                }
                if (DateTime.Now >= endDate && isDebug.ToLower() == "false")
                {
                    return new Messages { IsSuc = false, Code = 0, Message = "亲，活动已经结束了" };
                }
                var dc = new ActivityEntities();
                var qurey = dc.Bas_WxOrders.Where(t => t.openid == openID && t.OrderType == 2);
                if (qurey.Any() && isDebug.ToLower() == "false")
                {
                    return new Messages { IsSuc = false, Code = 0, Message = "亲，您已经抽过了，欢迎下次再来！" };
                }
                var rc = new RedisClient(RedisDatabaseIndex);

                var _day = DateTime.Now.Day.ToString();

                if (!rc.KeyExists(_day))
                {
                    Log.WriteLog("没找到奖池：OPENID:" + openID + ",SHOPID:" + _day);
                    return new Messages { IsSuc = false, Code = -1, Message = "没找到对店铺数据" };
                }
                var random = new Random((int)DateTime.Now.Ticks);
                var values = 0;
                var _newval = 88;
                while (true)
                {
                    var PoolLength = rc.GetListLength(_day);
                    var resultNum = random.Next((int)PoolLength) - 1;
                    values = rc.GetIntFromList(_day, resultNum);
                    rc.SetIntToList(_day, resultNum, _newval);
                    rc.RemoveStringFromList(_day, _newval.ToString());

                    var order = new Bas_WxOrders
                    {
                        openid = openID,
                        pid = values,
                        OrderType = 2,
                        createdate = DateTime.Now,
                        Finished = false
                    };
                    try
                    {
                        dc.Bas_WxOrders.Add(order);
                        dc.SaveChanges();
                        return new Messages { IsSuc = true, Code = 1, Message = values.ToString() };
                    }
                    catch (Exception ex)
                    {
                        Log.Error(ex);
                        return new Messages { IsSuc = false, Code = -1, Message = ex.Message };
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error("抽奖异常:" + ex);
                return new Messages { IsSuc = false, Code = -1, Message = "抽奖异常" };
            }
        }
        /// <summary>
        /// 初始化奖池写入到redis
        /// </summary>
        /// <param name="isFirst"></param>
        public string InitPrizePool(bool isFirst = false)
        {
            if (!isFirst)
                return "已经初始化";
            var rc = new RedisClient(RedisDatabaseIndex);
            var pattern = "Suc:";
            var ListInitData = InitData();
            if (ListInitData != null)
            {
                foreach (var item in ListInitData)
                {
                    if (rc.KeyExists(item.DrawDay)) rc.RemoveKey(item.DrawDay);
                    //删除当天店铺总抽奖数
                    if (rc.KeyExists(pattern + item.DrawDay)) rc.RemoveKey(pattern + item.DrawDay);
                    rc.AddIntToList(item.DrawDay, item.LotterArray);
                    Log.WriteLog("初始化：" + item.DrawDay + " 奖池成功");
                }
            }
            Log.WriteLog("初始化奖池时间:" + DateTime.Now);
            return "成功";
        }

        /// <summary>
        /// 初始化奖池
        /// </summary>
        /// <returns></returns>
        List<InitProductData> InitData()
        {
            var dc = new ActivityEntities();
            //奖品总数量
            var qurey = dc.Bas_prize.Where(t => t.LType == 1).ToList();
            var TotalLength = qurey.Sum(t => t.Qty);
            TotalLength = TotalLength * 2;
            //奖品当前库存
            var StockQurey = dc.V_ProductStock;
            if (qurey != null)
            {
                //日期
                var _day = DateTime.Now.Day;
                var _rate = 0.5;
                var list = new List<InitProductData>();
                try
                {
                    var lotteryQty = 0d;
                    int[] shopPool = new int[(int)TotalLength];
                    int l = 0;
                    var data = new InitProductData();
                    foreach (var item in qurey)
                    {
                        if (_day == 29 || isDebug.ToLower() == "true")
                        {
                            lotteryQty = Math.Round((int)item.Qty * _rate, 0);
                        }
                        else
                        {
                            var stock = StockQurey.FirstOrDefault(t => t.PID == item.PID);
                            lotteryQty = (double)stock.Qty;
                        }
                        //谢谢参与占总数的一半。
                        if (item.PID == (int)LotteryType.Thanks)
                            lotteryQty = (double)(_rate * TotalLength);
                        GeneratePool((int)lotteryQty, item.PID, ref shopPool, ref l);
                    }
                    //输出数组类型
                    ArrayItem<int> disrupter = new ArrayItem<int>(shopPool);
                    //输出一个打乱后数组
                    data.DrawDay = _day.ToString();
                    data.LotterArray = disrupter.GetDisruptedItems();
                    list.Add(data);
                    return list;
                }
                catch (Exception ex)
                {
                    Log.Error("奖池初始化错误：" + ex.Message);
                }
            }
            return null;
        }
        /// <summary>
        /// 生成奖池
        /// </summary>
        /// <returns></returns>
        void GeneratePool(int len, int type, ref int[] shopPool, ref int l)
        {
            for (int i = 0; i < len; i++)
            {
                if (type == (int)LotteryType.Thanks)
                    shopPool[l] = (int)LotteryType.Thanks;
                if (type == (int)LotteryType.FashionBike)
                    shopPool[l] = (int)LotteryType.FashionBike;
                if (type == (int)LotteryType.FashionCup)
                    shopPool[l] = (int)LotteryType.FashionCup;
                if (type == (int)LotteryType.MilletLamp)
                    shopPool[l] = (int)LotteryType.MilletLamp;
                if (type == (int)LotteryType.PhoneRing)
                    shopPool[l] = (int)LotteryType.PhoneRing;
                l++;
            }
        }
        public class InitProductData
        {
            public string DrawDay { get; set; }

            public int[] LotterArray { get; set; }
        }

        /// <summary>
        /// 返回结果
        /// </summary>
        public class Messages
        {
            public bool IsSuc { get; set; }
            public string Message { get; set; }
            public int Code { get; set; }
        }

        /// <summary>
        /// 奖品类型
        /// </summary>
        public enum LotteryType
        {
            /// <summary>
            /// 谢谢参与
            /// </summary>
            Thanks = 0,
            /// <summary>
            /// 自动车
            /// </summary>
            FashionBike = 1,
            /// <summary>
            /// 杯子
            /// </summary>
            FashionCup = 2,
            /// <summary>
            /// 小米灯
            /// </summary>
            MilletLamp = 3,
            /// <summary>
            /// 指环
            /// </summary>
            PhoneRing = 4
        }

    }

}
